package com.cctc.juc.demo.Bitc.Tmp.ADemo;

import java.util.concurrent.TimeUnit;

public class CWaitAndNotifyRunDemo {

    // 效果 3： A、B 交叉执行。

    private static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized (LOCK) {
                System.out.println("A -> print: 1");
                try {
                    System.out.println("A 自我阻塞，等待 B 执行...");
                    LOCK.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("A -> print: 2");
                System.out.println("A -> print: 3");
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (LOCK) {
                System.out.println("B -> print: 1");
                System.out.println("B -> print: 2");
                System.out.println("B -> print: 3");
                System.out.println("B 执行完成，唤醒 A 继续执行...");
                LOCK.notifyAll();
            }
        });

        t1.start();
        try {
            // t1 先启动，等待 1 秒后，t2 再启动，保证 t1 先获取到互斥锁。
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t2.start();
    }

}
